document.addEventListener('DOMContentLoaded', function() {
    // 删除按钮处理
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', async function(e) {
            e.preventDefault();
            const id = this.dataset.id;
            const type = this.dataset.type;
            
            if (!confirm('确定要删除吗？此操作不可恢复！')) {
                return;
            }

            try {
                const response = await fetch(`/admin/${type}/${id}/delete`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.success) {
                        // 删除成功，移除对应的行
                        this.closest('tr').remove();
                        showToast('删除成功', 'success');
                    } else {
                        showToast(data.error || '删除失败', 'error');
                    }
                } else {
                    const data = await response.json();
                    showToast(data.error || '删除失败', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('操作失败，请稍后重试', 'error');
            }
        });
    });

    // 保存点赞数
    document.querySelectorAll('.save-likes').forEach(btn => {
        btn.addEventListener('click', async function() {
            const id = this.dataset.id;
            const likesInput = this.parentElement.querySelector('.likes-input');
            const newLikes = parseInt(likesInput.value);
            
            if (isNaN(newLikes) || newLikes < 0) {
                showToast('请输入有效的数字', 'error');
                return;
            }

            try {
                const response = await fetch(`/admin/couple/${id}/set_likes`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ likes_count: newLikes })
                });

                if (response.ok) {
                    showToast('点赞数已更新', 'success');
                } else {
                    showToast('更新失败', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('操作失败，请稍后重试', 'error');
            }
        });
    });

    // 保存投票数
    document.querySelectorAll('.save-votes').forEach(btn => {
        btn.addEventListener('click', async function() {
            const id = this.dataset.id;
            const stayInput = this.parentElement.querySelector('.vote-input.stay');
            const divorceInput = this.parentElement.querySelector('.vote-input.divorce');
            const stayVotes = parseInt(stayInput.value);
            const divorceVotes = parseInt(divorceInput.value);
            
            if (isNaN(stayVotes) || isNaN(divorceVotes) || stayVotes < 0 || divorceVotes < 0) {
                showToast('请输入有效的数字', 'error');
                return;
            }

            try {
                const response = await fetch(`/admin/couple/${id}/set_votes`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        stay_votes: stayVotes,
                        divorce_votes: divorceVotes
                    })
                });

                if (response.ok) {
                    showToast('投票数已更新', 'success');
                } else {
                    showToast('更新失败', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('操作失败，请稍后重试', 'error');
            }
        });
    });

    // 评论点赞重置功能


    // 评论状态切换功能
    document.querySelectorAll('.toggle-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            const id = this.dataset.id;
            try {
                const response = await fetch(`/admin/comments/${id}/toggle`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.success) {
                        // 更新按钮文本和样式
                        this.textContent = data.is_hidden ? '已隐藏' : '正常';
                        this.classList.toggle('hidden');
                        showToast(data.is_hidden ? '评论已隐藏' : '评论已显示', 'success');
                    }
                } else {
                    showToast('操作失败', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('操作失败，请稍后重试', 'error');
            }
        });
    });
});

// 状态筛选处理
const statusFilter = document.getElementById('status-filter');
if (statusFilter) {
    statusFilter.addEventListener('change', function() {
        window.location.href = "{{ url_for('admin.manage_comments') }}?status=" + this.value;
    });
}

// Toast 提示函数
function showToast(message, type = 'info') {
    // 检查是否已存在 toast 容器
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }

    // 创建新的 toast
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;

    // 添加到容器
    container.appendChild(toast);

    // 设置消失动画
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(-20px)';
        
        // 移除元素
        setTimeout(() => {
            toast.remove();
            // 如果没有更多 toast，移除容器
            if (container.children.length === 0) {
                container.remove();
            }
        }, 300);
    }, 2000);
}

// 添加 Toast 样式
const style = document.createElement('style');
style.textContent = `
    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .toast {
        padding: 12px 24px;
        border-radius: 4px;
        background: rgba(0, 0, 0, 0.8);
        color: #fff;
        font-size: 14px;
        opacity: 1;
        transform: translateY(0);
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .toast.success {
        background: rgba(46, 204, 113, 0.9);
    }

    .toast.error {
        background: rgba(231, 76, 60, 0.9);
    }

    .toast.info {
        background: rgba(52, 152, 219, 0.9);
    }
`;
document.head.appendChild(style); 